﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 货品信息表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class GoodsinfoService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Goodsinfo> _goodsinfoRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public GoodsinfoService(SqlSugarRepository<Goodsinfo> goodsinfoRep, ISqlSugarClient sqlSugarClient)
    {
        _goodsinfoRep = goodsinfoRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询货品信息表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询货品信息表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<GoodsinfoOutput>> Page(PageGoodsinfoInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _goodsinfoRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.GoodsName.Contains(input.Keyword) || u.GoodsNumber.Contains(input.Keyword) || u.SpecificationsModels.Contains(input.Keyword) || u.ShelfLife.Contains(input.Keyword) || u.Desc.Contains(input.Keyword) || u.Barcodes.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsNumber), u => u.GoodsNumber.Contains(input.GoodsNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SpecificationsModels), u => u.SpecificationsModels.Contains(input.SpecificationsModels.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ShelfLife), u => u.ShelfLife.Contains(input.ShelfLife.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Desc), u => u.Desc.Contains(input.Desc.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Barcodes), u => u.Barcodes.Contains(input.Barcodes.Trim()))
            .WhereIF(input.GoodsTypeId != null, u => u.GoodsTypeId == input.GoodsTypeId)
            .WhereIF(input.vendorId != null, u => u.vendorId == input.vendorId)
            .WhereIF(input.CustomersId != null, u => u.CustomersId == input.CustomersId)
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .WhereIF(input.EarlyWarningDays != null, u => u.EarlyWarningDays == input.EarlyWarningDays)
            .WhereIF(input.CurrentInventory != null, u => u.CurrentInventory == input.CurrentInventory)
            .WhereIF(input.Unitid != null, u => u.Unitid == input.Unitid)
            .LeftJoin<Goodstypeinfo>((u, goodsType) => u.GoodsTypeId == goodsType.Id)
            .LeftJoin<Vendor>((u, goodsType, vendor) => u.vendorId == vendor.Id)
            .LeftJoin<Customers>((u, goodsType, vendor, customers) => u.CustomersId == customers.Id)
            .LeftJoin<Organizations>((u, goodsType, vendor, customers, unit) => u.Unitid == unit.Id)
            .Select((u, goodsType, vendor, customers, unit) => new GoodsinfoOutput
            {
                Id = u.Id,
                GoodsName = u.GoodsName,
                GoodsNumber = u.GoodsNumber,
                GoodsTypeId = u.GoodsTypeId,
                GoodsTypeDisplayName = $"{goodsType.goodstypeName}",
                SpecificationsModels = u.SpecificationsModels,
                vendorId = u.vendorId,
                vendorFkDisplayName = $"{vendor.VendorName}",
                CustomersId = u.CustomersId,
                CustomersFkDisplayName = $"{customers.CustomerName}",
                StoragePrice = u.StoragePrice,
                OutboundPrice = u.OutboundPrice,
                Sort = u.Sort,
                Status = u.Status,
                ShelfLife = u.ShelfLife,
                EarlyWarningDays = u.EarlyWarningDays,
                Desc = u.Desc,
                Barcodes = u.Barcodes,
                CurrentInventory = u.CurrentInventory,
                inventoryMoney = u.inventoryMoney,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                Unitid = u.Unitid,
                UnitFkDisplayName = $"{unit.OrganizationName}",
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取货品信息表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取货品信息表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Goodsinfo> Detail([FromQuery] QueryByIdGoodsinfoInput input)
    {
        return await _goodsinfoRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加货品信息表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加货品信息表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddGoodsinfoInput input)
    {
        var entity = input.Adapt<Goodsinfo>();
        return await _goodsinfoRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新货品信息表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新货品信息表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateGoodsinfoInput input)
    {
        var entity = input.Adapt<Goodsinfo>();
        await _goodsinfoRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除货品信息表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除货品信息表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteGoodsinfoInput input)
    {
        var entity = await _goodsinfoRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _goodsinfoRep.FakeDeleteAsync(entity);   //假删除
        //await _goodsinfoRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除货品信息表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除货品信息表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteGoodsinfoInput> input)
    {
        var exp = Expressionable.Create<Goodsinfo>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _goodsinfoRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _goodsinfoRep.FakeDeleteAsync(list);   //假删除
        //return await _goodsinfoRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataGoodsinfoInput input)
    {
        var goodsTypeIdData = await _goodsinfoRep.Context.Queryable<Goodstypeinfo>()
            .Select(u => new TreeSuperiorOutput
            {
                Value = u.Id,
                Label = $"{u.goodstypeName}" 
            }, true).ToTreeAsync(u => u.Children, u => u.SuperiorId, null);
        var vendorIdData = await _goodsinfoRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Goodsinfo>(input.FromPage, (u, r) => u.Id == r.vendorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var customersIdData = await _goodsinfoRep.Context.Queryable<Customers>()
            .InnerJoinIF<Goodsinfo>(input.FromPage, (u, r) => u.Id == r.CustomersId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var unitidData = await _goodsinfoRep.Context.Queryable<Organizations>()
            .InnerJoinIF<Goodsinfo>(input.FromPage, (u, r) => u.Id == r.Unitid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "goodsTypeId", goodsTypeIdData },
            { "vendorId", vendorIdData },
            { "customersId", customersIdData },
            { "unitid", unitidData },
        };
    }
    //1
    /// <summary>
    /// 导出货品信息表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出货品信息表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageGoodsinfoInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportGoodsinfoOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "货品信息表导出记录");
    }
    
    /// <summary>
    /// 下载货品信息表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载货品信息表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportGoodsinfoOutput>(), "货品信息表导入模板", (_, info) =>
        {
            if (nameof(ExportGoodsinfoOutput.GoodsTypeDisplayName) == info.Name) return _goodsinfoRep.Context.Queryable<Goodstypeinfo>().Select(u => $"{u.goodstypeName}").Distinct().ToList();
            if (nameof(ExportGoodsinfoOutput.vendorFkDisplayName) == info.Name) return _goodsinfoRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportGoodsinfoOutput.CustomersFkDisplayName) == info.Name) return _goodsinfoRep.Context.Queryable<Customers>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportGoodsinfoOutput.UnitFkDisplayName) == info.Name) return _goodsinfoRep.Context.Queryable<Organizations>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入货品信息表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入货品信息表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportGoodsinfoInput, Goodsinfo>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 货品类型
                    var goodsTypeIdLabelList = pageItems.Where(x => x.GoodsTypeDisplayName != null).Select(x => x.GoodsTypeDisplayName).Distinct().ToList();
                    if (goodsTypeIdLabelList.Any()) {
                        var goodsTypeIdLinkMap = _goodsinfoRep.Context.Queryable<Goodstypeinfo>().Where(u => goodsTypeIdLabelList.Contains($"{u.goodstypeName}")).ToList().ToDictionary(u => $"{u.goodstypeName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.GoodsTypeId = goodsTypeIdLinkMap.GetValueOrDefault(e.GoodsTypeDisplayName ?? "");
                            if (e.GoodsTypeId == null) e.Error = "货品类型链接失败";
                        });
                    }
                    // 链接 供应商
                    var vendorIdLabelList = pageItems.Where(x => x.vendorFkDisplayName != null).Select(x => x.vendorFkDisplayName).Distinct().ToList();
                    if (vendorIdLabelList.Any()) {
                        var vendorIdLinkMap = _goodsinfoRep.Context.Queryable<Vendor>().Where(u => vendorIdLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.vendorId = vendorIdLinkMap.GetValueOrDefault(e.vendorFkDisplayName ?? "");
                            if (e.vendorId == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 客户名称
                    var customersIdLabelList = pageItems.Where(x => x.CustomersFkDisplayName != null).Select(x => x.CustomersFkDisplayName).Distinct().ToList();
                    if (customersIdLabelList.Any()) {
                        var customersIdLinkMap = _goodsinfoRep.Context.Queryable<Customers>().Where(u => customersIdLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CustomersId = customersIdLinkMap.GetValueOrDefault(e.CustomersFkDisplayName ?? "");
                            if (e.CustomersId == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 单位
                    var unitidLabelList = pageItems.Where(x => x.UnitFkDisplayName != null).Select(x => x.UnitFkDisplayName).Distinct().ToList();
                    if (unitidLabelList.Any()) {
                        var unitidLinkMap = _goodsinfoRep.Context.Queryable<Organizations>().Where(u => unitidLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Unitid = unitidLinkMap.GetValueOrDefault(e.UnitFkDisplayName ?? "");
                            if (e.Unitid == null) e.Error = "单位链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Goodsinfo>>();
                    
                    var storageable = _goodsinfoRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.GoodsName?.Length > 32, "货品名称长度不能超过32个字符")
                        .SplitError(it => it.Item.GoodsNumber?.Length > 32, "货品编号长度不能超过32个字符")
                        .SplitError(it => it.Item.SpecificationsModels?.Length > 32, "规格型号长度不能超过32个字符")
                        .SplitError(it => it.Item.ShelfLife?.Length > 32, "保质期管理长度不能超过32个字符")
                        .SplitError(it => it.Item.Desc?.Length > 300, "备注长度不能超过300个字符")
                        .SplitError(it => it.Item.Barcodes?.Length > 32, "条码长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
